import { Button, Modal, Progress } from 'antd';
import { useState, useEffect, useRef } from 'react'
import MapSearchApi from '../../../utils/apis/MapSearchApi';
import FetchHelper from '../../../utils/helper/fetch-helper';
export default function AutoGeom(props) {
    const { listApi, params, keyField = 'cztmc', putApi = `/admin-api/ybyj/cztjcb` } = props;
    const [loading, setLoading] = useState();
    const [percent, setPercent] = useState(0);
    const [updateCount, setUpdateCount] = useState(0);
    const [total, setTotal] = useState(0);
    const [hasGeomCount, setHasGeomCount] = useState(0);
    const [noSearchCount, setNoSearchCount] = useState(0);

    const loadingRef = useRef();

    const mapSearch = (datas, index, callback, { total = 0, doneCount = 0 }) => {
        if (!loadingRef.current) {
            return;
        }
        const data = datas[index];
        if (!data) {
            callback();
            return;
        }
        const key = data?.[keyField];
        if (data.geom) {
            setPercent((doneCount + index + 1) / total);
            setHasGeomCount(c => ++c);
            mapSearch(datas, ++index, callback, { total, doneCount });
        } else {
            const zoneNames = ['翠屏区', '南溪区', '叙州区', '江安县', '长宁县', '高县', '珙县', '筠连县', '兴文县', '屏山县'];
            let searchValue = key;
            zoneNames.forEach(zoneName => {
                const strs = searchValue.split(zoneName);
                searchValue = strs?.[1] || strs?.[0];
            })
            MapSearchApi.search(searchValue).then(resp => {
                if (resp.message?.features?.length > 0) {
                    const features = [];
                    resp.message.features.forEach(feature => {
                        const attrs = feature.attributes || [];
                        const item = {};
                        resp.message.columns.forEach((col, i) => {
                            item[col.columnName] = attrs[i];
                        });
                        features.push(item);
                    });
                    const feature = features?.[0];
                    if (feature) {
                        const wkt = `POINT(${feature['X']} ${feature['Y']})`;
                        FetchHelper.putJson(putApi, {
                            ...data,
                            geom: wkt
                        }).then(resp => {
                            setPercent((doneCount + index + 1) / total);
                            setUpdateCount(c => {
                                return ++c;
                            })
                            mapSearch(datas, ++index, callback, { total, doneCount });
                        }).finally(e => {
                        })
                    } else {
                        setPercent((doneCount + index + 1) / total);
                        setNoSearchCount(c => ++c);
                        mapSearch(datas, ++index, callback, { total, doneCount });
                    }
                } else {
                    setPercent((doneCount + index + 1) / total);
                    setNoSearchCount(c => ++c);
                    mapSearch(datas, ++index, callback, { total, doneCount });
                }
            });
        }

    }

    const handler = (pageNum) => {
        if (!loadingRef.current) {
            return;
        }
        listApi({
            ...params,
            pageSize: 10,
            pageNum: pageNum,
        }).then(resp => {
            const datas = resp.rows;
            setTotal(resp.total)
            if (datas?.length) {
                mapSearch(datas, 0, () => {
                    handler(++pageNum);
                }, { total: resp.total, doneCount: (pageNum - 1) * 10 });
            } else {

            }
        })
    }

    return <>
        <Modal title="自动上图" open={props.visible} onCancel={e => {
            setLoading(false);
            loadingRef.current = false;
            props.onCancel?.()
        }} width={500} bodyStyle={{
            height: 300,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
        }} footer={[]}>
            {loading ? <div>
                <Progress strokeWidth={10} size={180} type="circle" percent={Math.round(percent * 10000) / 100}></Progress>
                <div className='layout-h' style={{
                    marginTop: 10
                }}>
                    <div className='fill'>已自动上图数据：</div>
                    <div>{updateCount}</div>
                </div>
                <div className='layout-h'>
                    <div className='fill'>已有坐标跳过数据：</div>
                    <div>{hasGeomCount}</div>
                </div>
                <div className='layout-h'>
                    <div className='fill'>未匹配上的数据：</div>
                    <div>{noSearchCount}</div>
                </div>
                <div className='layout-h'>
                    <div className='fill'>总数据量：</div>
                    <div>{total}</div>
                </div>
            </div> : <Button type="primary" size="large" onClick={e => {
                setLoading(true)
                loadingRef.current = true;
                if (listApi) {
                    handler(1);
                }
            }}>点击开始自动生成空间坐标</Button>}
        </Modal>
    </>;
}